package io.agora.openduo;

import android.app.Application;

import io.agora.openduo.agora.Config;
import io.agora.openduo.agora.EngineEventListener;
import io.agora.openduo.agora.Global;
import io.agora.openduo.agora.IEventListener;
import io.agora.openduo.utils.LogUtil;
import io.agora.rtc.RtcEngine;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.ResultCallback;
import io.agora.rtm.RtmCallManager;
import io.agora.rtm.RtmClient;

public class MyApp extends Application {
    private static final String TAG = "OpenDuoApplication";

    public static RtcEngine mRtcEngine;
    public static RtmClient mRtmClient;
    public static RtmCallManager rtmCallManager;
    public static EngineEventListener mEventListener;
    public static Config mConfig;
    public static Global mGlobal;

    @Override
    public void onCreate() {
        super.onCreate();
        initConfig();
    }

    private void initConfig() {
        mConfig = new Config();
        mGlobal = new Global();
    }


    public RtcEngine rtcEngine() {
        return mRtcEngine;
    }

    public RtmClient rtmClient() {
        return mRtmClient;
    }

    public void registerEventListener(IEventListener listener) {
        mEventListener.registerEventListener(listener);
    }

    public void removeEventListener(IEventListener listener) {
        mEventListener.removeEventListener(listener);
    }

    public RtmCallManager rtmCallManager() {
        return rtmCallManager;
    }

    public Config config() {
        return mConfig;
    }

    public Global global() {
        return mGlobal;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        destroyEngine();
    }

    private void destroyEngine() {
        RtcEngine.destroy();

        mRtmClient.logout(new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                LogUtil.e(TAG, "rtm client logout success");
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                LogUtil.e(TAG, "rtm client logout failed:" + errorInfo.getErrorDescription());
            }
        });
    }
}
